package vfs.server;

import org.xml.sax.SAXException;
import vfs.common.file.VirtualFileSystem;
import vfs.common.tty.Tty;
import vfs.server.config.Config;
import vfs.server.rmi.ServerRmiDispatcher;
import vfs.server.rmi.ServerRmiManager;

import javax.xml.parsers.ParserConfigurationException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;

/**
 * User: serge
 * Date: 15.11.13
 * Time: 1:18
 */
public class Main
{
    public static final VirtualFileSystem FILE_SYSTEM = new VirtualFileSystem();

    public static void main(String[] args)
    {
        Tty.println(Locale.WELCOME);

        try
        {
            Tty.println(Locale.LOADING_FS);
            FILE_SYSTEM.unserialize();
            Tty.println(Locale.LOADING_LOADED_OK);
        }
        catch (FileNotFoundException e)
        {
            Tty.println(Locale.LOADING_FS_EXC_FILE_NOT_FOUND);

            FILE_SYSTEM.newRoot();
            try
            {
                FILE_SYSTEM.serialize();
            }
            catch (IOException e1)
            {
                Tty.println(Locale.LOADING_FS_EXC);
                                e1.printStackTrace();
            }
            //            e.printStackTrace();
        }
        catch (ClassNotFoundException | IOException e)
        {
            Tty.println(Locale.LOADING_FS_EXC);
                        e.printStackTrace();
        }

        try
        {
            Tty.println(Locale.LOADING_CONFIG);
            Config.parse();
            Tty.println(Locale.LOADING_LOADED_OK);
        }
        catch (FileNotFoundException e)
        {
            Tty.println(Locale.LOADING_CONFIG_EXC_FILE_NOT_FOUND);
            e.printStackTrace();
        }
        catch (ParserConfigurationException | SAXException | IOException e)
        {
            e.printStackTrace();
        }

        try
        {
            ServerRmiDispatcher rmiDispatcher = new ServerRmiDispatcher();
            ServerRmiManager.getInstance().bind(Config.getListenPort(), rmiDispatcher);
            FILE_SYSTEM.setUsers(rmiDispatcher.getUsers());
            Tty.println(String.format(Locale.STARTED_FORMAT, Config.getListenPort()));
        }
        catch (RemoteException e)
        {
            Tty.println(Locale.BINDING_EXC);
            e.printStackTrace();
        }
        catch (AlreadyBoundException e)
        {
            Tty.println(String.format(Locale.BINDING_EXC_ALREADY_BOUND_FORMAT, Config.getListenPort()));
            e.printStackTrace();
        }
    }
}
